package com.xhwl.logistics.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhwl.common.enums.OrganizationTypeEnum;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.sdata.Account;
import com.xhwl.common.pojo.cent.sdata.Organization;
import com.xhwl.common.pojo.cent.sdata.Project;
import com.xhwl.common.pojo.cent.vehicle.VehcArea;
import com.xhwl.common.pojo.cent.vehicle.VehcParkingLot;
import com.xhwl.common.query.cent.sdata.ProjectQuery;
import com.xhwl.logistics.dao.VehcAreaDao;
import com.xhwl.logistics.dao.VehcParkingLotDao;
import com.xhwl.logistics.dao.VehcPassageDao;
import com.xhwl.common.pojo.cent.vehicle.VehcPassage;
import com.xhwl.common.query.cent.vehicle.PassageQuery;
import com.xhwl.logistics.enums.VehicleCodeEnum;
import com.xhwl.logistics.service.cent.IOrganizationService;
import com.xhwl.logistics.service.cent.IProjectService;
import com.xhwl.logistics.service.IVehcPassageService;
import com.xhwl.common.vo.cent.vehicle.PassageVO;
import com.xhwl.logistics.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Lu.Aaron
 * @since 2021-02-08
 */
//@Service
public class VehcPassageServiceImpl extends ServiceImpl<VehcPassageDao, VehcPassage> implements IVehcPassageService {
    @Autowired
    private VehcPassageDao vehcPassageDao;
    @Autowired
    private IProjectService projectService;
    @Autowired
    private VehcParkingLotDao vehcParkingLotDao;
    @Autowired
    private VehcAreaDao vehcAreaDao;
    @Autowired
    private IOrganizationService organizationService;
    @Override
    public void add(PassageVO passageVO, Short industryId) {
        //TODO 根据String syncManufacturer = passageVO.getSyncManufacturer()判断选择供应商，同步数据;
        //TODO 若syncManufacturer空，通过项目查询供应商，在进行同步数据
        if (null==passageVO.getAreaOrgId()) {
            throw new BusinessException("缺少必要参数：areaOrgId");
        }
        if (null==passageVO.getEnterpriseId()) {
            throw new BusinessException("缺少必要参数：enterpriseId");
        }
        if (null==passageVO.getLevel()) {
            throw new BusinessException("缺少必要项目层级数参数：level");
        }
        //TODO 1.调用主数据服务，在sdata_organization表新增通道
        Organization organization = new Organization();
        organization.setParentId(passageVO.getAreaOrgId());
        organization.setEnterpriseId(passageVO.getEnterpriseId());
        organization.setName(passageVO.getName());
        organization.setLevel(passageVO.getLevel()+3);
        organization.setIndustryId(industryId);

        //cent-common修改Organization setType
        organization.setType(OrganizationTypeEnum.PASSAGE.getId().intValue());

        ResultJson<Integer> resultJson = organizationService.create(organization, new Account());
        Integer orgId = resultJson.getResult();
        //TODO 2.新增通道
        VehcPassage vehcPassage = new VehcPassage();
        BeanUtils.copyProperties(passageVO,vehcPassage);
        vehcPassage.setOrgId(orgId);
        vehcPassageDao.insert(vehcPassage);
        //TODO 3.若需要同步则同步，根据接口厂商能力 true代表需要同步，false代表不需要同步

    }

    @Override
    public void edit(PassageVO passageVO, Short industryId) {
        //TODO 根据String syncManufacturer = passageVO.getSyncManufacturer()判断选择供应商，同步数据;
        //TODO 若syncManufacturer空，通过项目查询供应商，在进行同步数据
        if (Objects.isNull(passageVO.getOrgId())) {
            throw new BusinessException("缺少必要参数：orgId");
        }
        if (Objects.isNull(passageVO.getId())) {
            throw new BusinessException("缺少必要参数：id");
        }
        if (null==passageVO.getEnterpriseId()) {
            throw new BusinessException("缺少必要参数：enterpriseId");
        }
        if (null==passageVO.getLevel()) {
            throw new BusinessException("缺少必要项目层级数参数：level");
        }
        //TODO 1.调用主数据服务，在sdata_organization表修改通道
        Organization organization = new Organization();
        organization.setId(passageVO.getOrgId());
        organization.setName(passageVO.getName());
        organization.setParentId(passageVO.getAreaOrgId());
        organization.setEnterpriseId(passageVO.getEnterpriseId());
        organization.setLevel(passageVO.getLevel()+3);
        organization.setIndustryId(industryId);

        //修改Organization setType
        organization.setType(OrganizationTypeEnum.PASSAGE.getId().intValue());

        organizationService.update(organization, new Account());
        //TODO 2.修改通道
        VehcPassage vehcPassage = new VehcPassage();
        BeanUtils.copyProperties(passageVO,vehcPassage);
        vehcPassageDao.updateById(vehcPassage);
    }

    @Override
    public void delete(Integer id, Short industryId) {
        //TODO 通过id查询对应的projectId再查询对应的供应商
        //TODO 1.调用主数据服务，在sdata_organization表删除通道
        VehcPassage vehcPassageQuery = vehcPassageDao.selectById(id);
        organizationService.delete(vehcPassageQuery.getOrgId(), null);
        //TODO 2.删除通道
        vehcPassageDao.deleteById(id);
    }

    @Override
    public Page<VehcPassage> passagePage(PassageQuery passageQuery) {

        String parkingLotName = passageQuery.getParkingLotName();
        String name = passageQuery.getName();
        List<Integer> queryProjectIds =  passageQuery.getProjectIds();
        Integer projectId = passageQuery.getProjectId();
        if (null==queryProjectIds&&null==projectId) {
            throw new BusinessException(VehicleCodeEnum.PROJECT_ID_LACK.description);
        }
        if (null!=queryProjectIds&&queryProjectIds.isEmpty()&&null==projectId) {
            throw new BusinessException(VehicleCodeEnum.PROJECT_ID_LACK.description);
        }
        Page<VehcPassage> page = new Page<>();
        page.setCurrent(passageQuery.getCurrent());
        page.setSize(passageQuery.getPageSize());
        QueryWrapper<VehcPassage> wrapper = new QueryWrapper<>();
        //通过parkingLotName模糊搜索parkingLotId
        if (StringUtils.isNotBlank(parkingLotName)) {
            List<VehcParkingLot> vehcParkingLots = vehcParkingLotDao.selectList(new QueryWrapper<VehcParkingLot>().like("name", parkingLotName));
            if (vehcParkingLots.isEmpty()) {
                //通过名称过滤到无此车场则返回空
                return page;
            }
            List<Integer> parkingLotIds = vehcParkingLots.stream().map(vp -> vp.getId()).collect(Collectors.toList());
            if (!parkingLotIds.isEmpty()) {
                wrapper.in("parking_lot_id",parkingLotIds);
            }

        }

        if (StringUtils.isNotBlank(name)) {
            wrapper.like("name",name);
        }
        if (null!=queryProjectIds&&!queryProjectIds.isEmpty()) {
            wrapper.in("project_id",queryProjectIds);
        }
        if (null!=projectId) {
            wrapper.eq("project_id",projectId);
        }
        Page<VehcPassage> passagePage = vehcPassageDao.selectPage(page, wrapper);
        List<VehcPassage> records = passagePage.getRecords();
        if (!records.isEmpty()) {
            //根据项目id获取项目名称
            List<Integer> projectIds = records.stream().map(v -> v.getProjectId()).collect(Collectors.toList());
            ProjectQuery projectQuery = new ProjectQuery();
            projectQuery.withIdList(projectIds);
            List<Project> projects = projectService.list(projectQuery, null);
            //根据区域id查询区域名称
            List<Integer> areaIds = records.stream().map(v -> v.getAreaId()).collect(Collectors.toList());
            List<VehcArea> vehcAreas= vehcAreaDao.selectBatchIds(areaIds);
            //车场id查询车场名称
            Set<Integer> parkingLotIdSet = records.stream().map(v -> v.getParkingLotId()).collect(Collectors.toSet());
            List<VehcParkingLot> parkingLotList = vehcParkingLotDao.selectList(new QueryWrapper<VehcParkingLot>().in("id", parkingLotIdSet));
            records.forEach(vp->{
                projects.forEach(p->{
                    if (vp.getProjectId().equals(p.getId())) {
                        vp.setProjectName(p.getName());
                    }
                });
                if (!vehcAreas.isEmpty()) {
                    vehcAreas.forEach(v->{
                        if (vp.getAreaId().equals(v.getId())) {
                            vp.setAreaName(v.getName());
                            vp.setAreaOrgId(v.getOrgId());
                        }
                    });
                }
                if (!parkingLotList.isEmpty()) {
                    parkingLotList.forEach(p->{
                        if (p.getId().equals(vp.getParkingLotId())) {
                            vp.setParkingLotName(p.getName());
                            vp.setParkingLotOrgId(p.getOrgId());
                        }
                    });
                }

            });
        }

        return passagePage;
    }

    @Override
    public List<VehcPassage> list(PassageQuery passageQuery) {
        QueryWrapper<VehcPassage> wrapper = new QueryWrapper<>();
        if (Objects.nonNull(passageQuery.getProjectId())) {
            wrapper.eq("project_id",passageQuery.getProjectId());
        }
        if (Objects.nonNull(passageQuery.getProjectIds())&&!passageQuery.getProjectIds().isEmpty()) {
            wrapper.in("project_id", passageQuery.getProjectIds());
        }
        if (Objects.nonNull(passageQuery.getAreaId())) {
            wrapper.like("area_id",passageQuery.getAreaId());
        }
        if (Objects.nonNull(passageQuery.getOrgId())) {
            wrapper.like("org_id",passageQuery.getOrgId());
        }
        return vehcPassageDao.selectList(wrapper);
    }
}
